package com.work.biz.controller;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.work.biz.domain.BizWorkDetail;
import com.work.biz.domain.BizWorkDetailVo;
import com.work.biz.service.IBizWorkDetailService;
import com.work.common.utils.file.FileUtils;
import com.work.mp.service.impl.MpTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.work.common.annotation.Log;
import com.work.common.core.controller.BaseController;
import com.work.common.core.domain.AjaxResult;
import com.work.common.enums.BusinessType;
import com.work.biz.domain.BizWork;
import com.work.biz.service.IBizWorkService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作业Controller
 *
 * @author lee
 * @date 2021-04-22
 */
@RestController
@RequestMapping("/api/biz/work")
@Api(value = "作业api", tags = {"发布作业,作业查询接口"})
public class BizWorkController extends BaseController {
    @Autowired
    private IBizWorkService bizWorkService;
    @Autowired
    private MpTokenService tokenService;
    @Autowired
    private IBizWorkDetailService bizWorkDetailService;

    /**
     * 查询发布的作业列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询我发布的作业列表", httpMethod = "GET", notes = "成功：0，验证失败：500")
    public AjaxResult list(
            @ApiParam(value = "用户token", required = true)
            @RequestHeader("tk")
                    String tk
    ) {
        BizWork bizWork = new BizWork();
        bizWork.setCreatorId(tokenService.getUserId(tk));
        List<BizWork> list = bizWorkService.selectBizWorkList(bizWork);
        return AjaxResult.success(list);
    }

    /**
     * 学生查询作业列表
     */
    @PostMapping("/workList")
    @ApiOperation(value = "学生查询作业列表", httpMethod = "POST", notes = "成功：0，验证失败：500")
    public AjaxResult workList(
            @ApiParam(value = "用户token", required = true)
            @RequestHeader("tk")
                    String tk,
            @ApiParam(value = "作业内容")
            @RequestBody BizWork bizWork
    ) {
        BizWorkDetailVo bizWorkDetail = new BizWorkDetailVo();
        bizWorkDetail.setUserId(tokenService.getUserId(tk));
        bizWorkDetail.setWork(bizWork);
        List<BizWorkDetailVo> list = bizWorkDetailService.selectBizWorkDetailList(bizWorkDetail);
        return AjaxResult.success(list);
    }

    /**
     * 获取作业详细信息
     */
    @GetMapping(value = "/detail/{workId}")
    @ApiOperation(value = "教师查询作业详细信息", httpMethod = "GET", notes = "成功：0，验证失败：500")
    public AjaxResult getInfo(
            @ApiParam(value = "作业ID", required = true)
            @PathVariable("workId") Long workId) {
        return AjaxResult.success(bizWorkService.selectBizWorkDetailById(workId));
    }

    /**
     * 发布作业
     */
    @Log(title = "作业", businessType = BusinessType.INSERT)
    @PostMapping("/addText")
    @ApiOperation(value = "发布文本作业", httpMethod = "POST", notes = "成功：0，验证失败：500")
    public AjaxResult addText(
            HttpServletRequest request,
            @ApiParam(value = "用户token", required = true)
            @RequestHeader("tk")
                    String tk,
            @ApiParam(value = "作业内容")
            @RequestBody BizWork bizWork
    ) {
        bizWork.setCreatorId(tokenService.getUserId(tk));
        return toAjax(bizWorkService.insertBizWork(bizWork));
    }

    /**
     * 发布作业
     */
    @Log(title = "作业", businessType = BusinessType.INSERT)
    @PostMapping("/addDoc")
    @ApiOperation(value = "发布文档作业", httpMethod = "POST", notes = "成功：0，验证失败：500")
    public AjaxResult addDoc(
            HttpServletRequest request,
            @ApiParam(value = "用户token", required = true)
            @RequestHeader("tk")
                    String tk,
            @ApiParam(value = "作业内容")
                    BizWork bizWork,
            @ApiParam(value = "作业文件")
                    MultipartFile file
    ) {
        if ("2".equals(bizWork.getWorkType())) {
            try {
                InputStream is = file.getInputStream();
                String content = FileUtils.readInputStream(is);
                bizWork.setWorkContent(content);
                bizWork.setCreatorId(tokenService.getUserId(tk));
                bizWork.setRemark(file.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return toAjax(bizWorkService.insertBizWork(bizWork));
    }

    /**
     * 修改作业
     */
    @Log(title = "作业", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizWork bizWork) {
        return toAjax(bizWorkService.updateBizWork(bizWork));
    }

    /**
     * 提交作业
     */
    @Log(title = "作业", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "学生提交作业", httpMethod = "POST", notes = "成功：0，验证失败：500")
    @PostMapping("/submit")
    public AjaxResult submit(
            @ApiParam(value = "作业详情ID")
                    Long detailId,
            @ApiParam(value = "作业文件名")
                    String fileName,
            @ApiParam(value = "作业文件")
                    MultipartFile file) {

        BizWorkDetail bizWorkDetail = new BizWorkDetail();
        bizWorkDetail.setDetailId(detailId);
        try {
            InputStream is = file.getInputStream();
            String content = FileUtils.readInputStream(is);
            bizWorkDetail.setSubmitContent(content);
            bizWorkDetail.setStatus("1");
            bizWorkDetail.setRemark(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return toAjax(bizWorkDetailService.updateBizWorkDetail(bizWorkDetail));
    }

    /**
     * 学生下载作业
     */
    @PostMapping("/workContent/{workId}")
    @ApiOperation(value = "下载发布的作业", httpMethod = "POST", notes = "成功：0，验证失败：500")
    public void workContent(
            @PathVariable Long workId, HttpServletResponse response
    ) {
        BizWork bizWork = bizWorkService.selectBizWorkById(workId);
        String fileName = bizWork.getRemark();
        OutputStream outputStream = null;
        try {
            byte[] bytes = FileUtils.readIoStringToFile(bizWork.getWorkContent());

            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.substring(fileName.lastIndexOf("/") + 1) + "\"");
            response.addHeader("Content-Length", "" + bytes.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 老师下载作业
     */
    @GetMapping("/submitContent/{detailId}")
    @ApiOperation(value = "下载提交的作业", httpMethod = "GET", notes = "成功：0，验证失败：500")
    public void submitContent(
            @PathVariable Long detailId, HttpServletResponse response
    ) {
        BizWorkDetail workDetail = bizWorkDetailService.selectBizWorkDetailById(detailId);
        String fileName = workDetail.getRemark();
        OutputStream outputStream = null;
        try {
            byte[] bytes = FileUtils.readIoStringToFile(workDetail.getSubmitContent());
            //response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.substring(fileName.lastIndexOf("/") + 1) + "\"");
            response.setHeader("Content-Disposition", "attachment; filename=" +new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + bytes.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除作业
     */
    @Log(title = "作业", businessType = BusinessType.DELETE)
    @DeleteMapping("/{workIds}")
    public AjaxResult remove(@PathVariable Long[] workIds) {
        return toAjax(bizWorkService.deleteBizWorkByIds(workIds));
    }
}
